<template>
  <section class="todoapp">
    <todu-header @add="handleadd"></todu-header>
    <todu-main :list="list2" @del="handleDel" @state="handlestate" @changeAll="handleAll"></todu-main>
    <todu-footer
      :list="list"
      @clear="handleclear"
      :flag="flag"
      @changeflag="
        (val) => {
          flag = val;
        }
      "
    ></todu-footer>
    <!-- This section should be hidden by default and shown when there are todos -->

    <!-- This footer should be hidden by default and shown when there are todos -->
  </section>
</template>

<script>
import ToduFooter from "./components/ToduFooter.vue";
import ToduHeader from "./components/ToduHeader.vue";
import ToduMain from "./components/ToduMain.vue";
export default {
  components: { ToduMain, ToduHeader, ToduFooter },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('todo-list')) || [],
      // list: [
      //   { id: 12, name: "吃饭", isDone: false },
      //   { id: 14, name: "听歌", isDone: true },
      //   { id: 23, name: "洗澡", isDone: true },
      //   { id: 34, name: "睡觉", isDone: false },
      //   { id: 35, name: "游戏", isDone: false },
      // ],
      flag: 1, //1全部任务  2进行中   3已完成
    };
  },
  methods: {
    //删除数据
    handleDel(id) {
      console.log(id);
      this.list = this.list.filter((item) => item.id !== id);
    },
    //添加数据
    handleadd(todoname) {
      //像数组开头添加数据
      this.list.unshift({ id: +new Date(), name: todoname, isDone: false });
    },
    //改变状态
    handlestate(id) {
      const row = this.list.find((item) => {
        return item.id === id;
      });
      row.isDone = !row.isDone;
    },
    //清除已完成的数据
    handleclear() {
      // filter 方法 过滤出已完成的，保留未完成的
      return (this.list = this.list.filter((item) => item.isDone === false));
    },
    handleAll(val){
      this.list.forEach(item=>(item.isDone = val))
    }
  },
  //计算属性
  computed: {
    list2() {
      if (this.flag === 1) {
        return this.list;
      } else if (this.flag === 2) {
        return this.list.filter((item) => item.isDone === false);
      } else {
        return this.list.filter((item) => item.isDone === true);
      }
    },
  },
  //侦听器
  watch: {
    list:{
      handler(val){
        localStorage.setItem('todo-list',JSON.stringify(val))
      },
      deep:true
    }
  }
};
</script>

<style></style>

